<template>
  <div class="page-container">
    <div class="in-container">
      <el-row :gutter="8">
        <el-col :span="10">
          <AppTitleBox class="app-title-box" title="模板管理">
            <template #button>
              <el-button @click="addDict()" link type="primary">添加</el-button>
            </template>
            <AppSearchForm @submit="search()" @reset="reset()">
              <el-form-item>
                <el-input
                  v-model="state.query.name"
                  clearable
                  placeholder="输入模板名称搜索"
                  style="width: 200px"
                />
              </el-form-item>
            </AppSearchForm>
            <AppPageTable
              stripe
              :data="state.dictTableData.data"
              :singleHighLight="true"
              :autostyle="'height: calc(100% - 32px);'"
              :option="state.dictTableData.option"
              @change="getList()"
              @singleClick="(data) => singleClickGetDetail(data)"
            >
              <el-table-column
                :show-overflow-tooltip="true"
                prop="freightTemplateName"
                label="名称"
              />
              <el-table-column label="操作" width="90px" fixed="right">
                <template #default="scope">
                  <el-button
                    @click.stop="updateDict(scope.row)"
                    link
                    type="primary"
                    >编辑</el-button
                  >
                  <el-popconfirm
                    title="确定删除本条数据吗？"
                    @confirm="deleteDict(scope.row)"
                  >
                    <template #reference>
                      <el-button link type="danger">删除</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </AppPageTable>
          </AppTitleBox>
        </el-col>
        <el-col :span="14">
          <AppTitleBox class="app-title-box" title="模板详情">
            <template #button>
              <el-button
                @click="addDictDetail()"
                link
                v-show="state.dictDetailTableData.dictName"
                type="primary"
                >添加</el-button
              >
            </template>
            <div
              v-show="state.dictDetailTableData.dictName"
              style="height: 100%"
            >
              <AppPageTable
                stripe
                :data="state.dictDetailTableData.data"
                @change="getDetail()"
                :autostyle="'height: 100%;'"
                :option="state.dictDetailTableData.option"
              >
                <el-table-column prop="feename" label="费用名称" />
                <el-table-column prop="currencycode" label="币种" />
                <el-table-column prop="price" label="单价" />
                <el-table-column prop="isincome" label="类型">
                  <template #default="scope">
                    {{ scope.row.isincome == 0?'应付':'应收' }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="90px" fixed="right">
                  <template #default="scope">
                    <el-button
                      @click="updateDictDetail(scope.row)"
                      link
                      type="primary"
                      >编辑</el-button
                    >
                    <el-popconfirm
                      title="确定删除本条数据吗？"
                      @confirm="deleteDictDetail(scope.row)"
                    >
                      <template #reference>
                        <el-button link type="danger">删除</el-button>
                      </template>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </AppPageTable>
            </div>
            <div v-show="!state.dictDetailTableData.dictName">
              点击模板查看详情
            </div>
          </AppTitleBox>
        </el-col>
      </el-row>
    </div>
  </div>
  <!-- 模板弹窗 -->
  <el-dialog
    width="500px"
    v-model="state.dictdialogData.show"
    :title="state.dictdialogData.title"
  >
    <el-form
      :model="state.dictData"
      :rules="state.dictRules"
      label-width="80px"
      ref="dictForm"
    >
      <el-form-item prop="name" label="名称">
        <el-input v-model="state.dictData.freightTemplateName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelDict" link>取消</el-button>
        <el-button type="primary" @click="submitDict"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 模板详情弹窗 -->
  <el-dialog
    width="500px"
    v-model="state.dictDetailDialogData.show"
    :title="state.dictDetailDialogData.title"
    @close="dictDetailDialogClose"
  >
    <el-form
      :model="state.dictDetailData"
      :rules="state.dictDetailRules"
      label-width="80px"
      ref="dictDetailForm"
    >
      <el-form-item prop="feename" label="费用名称">
        <el-select
          v-model="state.dictDetailData.feename"
          filterable
          remote
          reserve-keyword
          placeholder="请选择"
          ref="feeNameRef"
          size="small"
          :remote-method="selectFeeNameOptions"
          :loading="state.feeNameSelect.loading"
          style="width: 100%"
          @click="selectFeeNameOptions('')"
          @blur="checkFormItem('feename')"
        >
          <el-option
            v-for="item in state.feeNameSelect.options"
            :key="item.id"
            :label="item.label"
            :value="item.value"
            @click="getFeeNameOption(item)"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="currencycode" label="币种">
        <el-select
          v-model="state.dictDetailData.currencycode"
          filterable
          remote
          reserve-keyword
          placeholder="请选择"
          ref="currencyRef"
          size="small"
          :remote-method="selectCurrencyOptions"
          :loading="state.currencySelect.loading"
          style="width: 100%"
          @click="selectCurrencyOptions('')"
          @blur="checkFormItem('currencycode')"
        >
          <el-option
            v-for="item in state.currencySelect.options"
            :key="item.id"
            :label="item.label"
            :value="item.value"
            @click="getCurrencyOption(item)"
          >
            {{ item.showLabel }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="price" label="金额">
        <el-input
          v-model="state.dictDetailData.price"
          ref="priceRef"
          size="small"
          @input="state.dictDetailData.price = validateOnlyNumberTwo(state.dictDetailData.price)"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="应收/应付">
        <el-radio-group v-model="state.dictDetailData.isincome" class="ml-4">
          <el-radio :value="0" size="small">应付</el-radio>
          <el-radio :value="1" size="small">应收</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelDictDetail" link>取消</el-button>
        <el-button type="primary" @click="submitDictDetail"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, reactive, watch, nextTick } from "vue";
import AppSearchForm from "@/components/AppSearchForm.vue";
import AppPageTable, { useTableOption } from "@/components/AppPageTable2";
import AppTitleBox from "@/components/AppTitleBox.vue";
import request from "@/public/request";
import { ElMessage, ElMessageBox } from "element-plus";
import { validateOnlyNumberTwo, validateNumber } from '@/utils/validate.js'

const state = reactive({
  query: {
    name: "",
  },
  dictTableData: {
    data: [],
    option: useTableOption(),
  },
  dictdialogData: {
    show: false,
    title: "",
  },
  dictData: {
    freightTemplateName: "",
  },
  dictRules: {
    freightTemplateName: [
      { required: true, message: "请输入名称", trigger: "blur" },
    ],
  },
  //详情表格数据
  dictDetailTableData: {
    id: "",
    dictName: "",
    data: [],
    option: useTableOption(),
  },
  //详情表单数据
  dictDetailData: {
    feename: "",
    feecode: "",
    currencycode: "",
    currencyname: "",
    value: "",
    isincome: 0,
    price: 0,
  },
  //详情表单规则
  dictDetailRules: {
    feename: [{ required: true, message: "请选择费用", trigger: "blur" }],
    currencycode: [{ required: true, message: "请选择币种", trigger: "blur" }],
    price: [{ required: true, message: "请输入金额", trigger: "blur" }],
  },
  //详情弹窗数据
  dictDetailDialogData: {
    show: false,
    title: "新增模板详情",
  },
  // 费用列表
  feeNameSelect: {
    loading: false,
    options: [],
  },
  // 币种列表
  currencySelect: {
    loading: false,
    options: [],
  },
});
/**
 * 查询费用名称数据
 * @param {string} query - 输入内容查询
 */
const selectFeeNameOptions = (query) => {
  state.feeNameSelect.loading = true;
  request
    .get("/api/base/feetype/query", {
      PageIndex: 1,
      PageSize: 10,
      KeyWords: query,
    })
    .then((res) => {
      state.feeNameSelect.options = res.content.map((t) => {
        return {
          id: t.id,
          label: t.feeName,
          value: t.feeName,
          currency: t.currency,
          code: t.feeCode,
        };
      });
    })
    .finally(() => (state.feeNameSelect.loading = false));
};
/**
 * 费用选择的option
 * @param {object} item - 选择的option
 */
const getFeeNameOption = (item) => {
  state.dictDetailData.feename = item.value;
  state.dictDetailData.feecode = item.code;

  state.dictDetailData.currencycode = item.currency.split("|")[0];
  state.dictDetailData.currencyname = item.currency.split("|")[1];

  checkFormItem('feename');
};
/**
 * 查询币种数据
 * @param {string} query - 输入内容查询
 */
const selectCurrencyOptions = (query) => {
  state.currencySelect.loading = true;
  request
    .get("/api/base/currency/dropdownlist", {
      // PageIndex: 1,
      // PageSize: 10,
      KeyWords: query,
    })
    .then((res) => {
      state.currencySelect.options = res.map((t) => {
        return {
          id: t.id,
          label: t.currencyName,
          value: t.currencyCode,
          showLabel: `${t.currencyCode}|${t.currencyName}`,
        };
      });
    })
    .finally(() => (state.currencySelect.loading = false));
};
/**
 * 币种的option
 * @param {object} item - 选择的option
 */
const getCurrencyOption = (item) => {
  state.dictDetailData.currencycode = item.value;
  state.dictDetailData.currencyname = item.label;
  checkFormItem('currencycode');
};
// 获取数据列表
const search = () => {
  state.dictTableData.option.page = 1;
  getList();
};
// 重置
const reset = () => {
  state.query = {
    name: "",
    date: [],
    enabled: "",
  };
  state.dictTableData.option.page = 1;
  getList();
};
// 新增模板
const addDict = () => {
  state.dictData = {
    freightTemplateName: "",
  };
  state.dictdialogData.title = "添加费用模板";
  state.dictdialogData.show = true;
};
// 获取数据列表
const getList = () => {
  state.dictTableData.option.loading = true;
  request
    .get("/api/frighttemplate/QueryPageList", {
      PageIndex: state.dictTableData.option.page,
      PageSize: state.dictTableData.option.pageSize,
      keyWords: state.query.name,
    })
    .then((res) => {
      state.dictTableData.data = res.content;
      state.dictTableData.option.total = res.totalElements;
    })
    .catch((err) => {
      ElMessage.error("表格数据请求失败");
    })
    .finally(() => {
      state.dictTableData.option.loading = false;
    });
};
const updateDict = (data) => {
  state.dictdialogData.title = "编辑模板";
  state.dictData = JSON.parse(JSON.stringify(data));
  state.dictdialogData.show = true;
};
const deleteDict = (data) => {
  if (state.dictDetailTableData.id && state.dictDetailTableData.id == data.id) {
    state.dictDetailTableData = {
      id: "",
      dictName: "",
      data: [],
      option: useTableOption(),
    };
  }
  request
    .post("/api/frighttemplate/delete", { idArray: [data.id] })
    .then((res) => {
      if (res.status) {
        ElMessage.success(res.message);
        getList();
      } else {
        ElMessage.error(res.message);
      }
    });
};
const cancelDict = () => {
  state.dictdialogData.show = false;
};
const submitDict = () => {
  let url = "";
  if (state.dictData.id) {
    url = "/api/frighttemplate/update";
  } else {
    url = "/api/frighttemplate/create";
  }

  request.post(url, state.dictData).then((res) => {
    if (res.status) {
      ElMessage.success(res.message);
      getList();
      cancelDict();
    } else {
      ElMessage.error(res.message);
    }
  });
  state.dictdialogData.show = false;
};
const singleClickGetDetail = (data) => {
  state.dictDetailTableData.id = data.id;
  state.dictDetailTableData.dictName = data.freightTemplateName;
  getDetail();
};
const getDetail = () => {
  state.dictDetailTableData.option.loading = true;
  request
    .get("/api/freightdetail/querypagelist", {
      PageIndex: state.dictDetailTableData.option.page,
      PageSize: state.dictDetailTableData.option.pageSize,
      FreightTemplateId: state.dictDetailTableData.id,
    })
    .then((res) => {
      res.content = res.content.map((item) => {
        item.belong = state.dictDetailTableData.dictName;
        return item;
      });
      state.dictDetailTableData.data = res.content;
      state.dictDetailTableData.option.total = res.totalElements;
    })
    .finally(() => {
      state.dictDetailTableData.option.loading = false;
    });
};
const addDictDetail = () => {
  state.dictDetailDialogData.title = "新增模板详情";
  state.dictDetailDialogData.show = true;
};
const updateDictDetail = (data) => {
  state.dictDetailData = JSON.parse(JSON.stringify(data));
  state.dictDetailDialogData.title = "编辑模板详情";
  state.dictDetailDialogData.show = true;
};
const deleteDictDetail = (data) => {
  request
    .post("/api/freightdetail/delete", { idArray: [data.id] })
    .then((res) => {
      if (res.status) {
        ElMessage.success(res.message);
        getDetail();
      } else {
        ElMessage.error(res.message);
      }
    });
};

const dictForm = ref();
const dictDetailForm = ref();

const cancelDictDetail = () => {
  state.dictDetailDialogData.show = false;
};
const submitDictDetail = async () => {
  let res = await dictDetailForm.value.validate();
  if(res){
    let url = "";
    if (state.dictDetailData.id) {
      url = "/api/freightdetail/update";
    } else {
      url = "/api/freightdetail/create";
      state.dictDetailData.freightTemplateId = state.dictDetailTableData.id;
    }
    request.post(url, state.dictDetailData).then((res) => {
      if (res.status) {
        ElMessage.success(res.message);
        getDetail();
        cancelDictDetail();
      } else {
        ElMessage.error(res.message);
      }
    });
    state.dictDetailDialogData.show = false;
  }
};



const dictDetailDialogClose = () => {
  dictDetailForm.value.resetFields();
  state.dictDetailData = {
    feename: "",
    feecode: "",
    currencycode: "",
    currencyname: "",
    value: "",
    isincome: 0,
    price: 0
  }
}

const checkFormItem = (key) => {
  dictDetailForm.value.validateField(key);
}

watch(state.dictdialogData.show, (newVal) => {
  if (!newVal) {
    nextTick(() => {
      state.dictData = {
        freightTemplateName: "",
      };
      dictForm.value.resetFields();
    });
  }
});

watch(state.dictDetailDialogData.show, (newVal) => {
  if (!newVal) {
    nextTick(() => {
      state.dictDetailData = {
        label: "",
        value: "",
        dictSort: 999,
      };
      dictDetailForm.value.resetFields();
    });
  }
});

onMounted(() => {
  getList();
  selectCurrencyOptions();
});
</script>

<style lang="scss" scoped>
.el-row {
  height: 100%;
}

.el-col {
  height: 100%;
}
.app-title-box {
  height: 100%;
  box-sizing: border-box;
}
</style>
